package com.hlbspringcloud.mq;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @Author huanglibin
 * @Project mq
 * @Description 工作队列 消费者2
 * @Date 2020-12-02-16-12-05
 * @Version 1.0
 */
public class WorkReceiver2 {
    /**
     * 队列名称
     */
    public final static String QUEUE_NAME = "work query";

    /**
     * 接收消息
     * @throws Exception
     */
    public void receiveMessage() throws Exception{
        //1.获取连接
        Connection rabbitmqConnection = RabbitmqUntil.getRabbitmqConnection();
        //2.创建管道
        Channel channel = rabbitmqConnection.createChannel();
        //3.创建队列（如果队列已存在，则不处理）
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);
        //4.创建消费用户
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("接收者2:"+new String(body,"utf-8"));
                //模拟业务处理，1秒
                try {
                    Thread.sleep(1000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        };
        /**
         * 监听rabbitmq队列信息（此时程序会自动堵塞，当有数据到达时，处理相应的数据）
         * 参数1：队列名
         * 参数2：是否自动问答
         * 参数3：消费用户
         */
        channel.basicConsume(QUEUE_NAME,true,consumer);
    }

    public static void main(String[] args)throws Exception {
        WorkReceiver2 workReceiver2 = new WorkReceiver2();
        workReceiver2.receiveMessage();
    }
}
